package com.syf.starter.core.netty.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class ServerIdleHandle extends IdleStateHandler {
    private String serverName;

    private int maxIdleSends;

    public ServerIdleHandle(String serverName) {
        this(serverName, 360);
    }

    public ServerIdleHandle(String serverName, int maxIdleSends) {
        super(0, 0, maxIdleSends);
        this.serverName = serverName;
        this.maxIdleSends = maxIdleSends;
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        if (log.isDebugEnabled()) {
            log.debug("在{}中，发现客户端连接：[{}/{}]，空闲[{}]秒，服务端将关闭此空闲连接!", serverName, inetSocketAddress.getHostName(), inetSocketAddress.getPort(), maxIdleSends);
        }
        ctx.channel().close();
    }
}
